#! /usr/bin/env bash

_main() {
  local i=1 cmd

  while [[ "$i" -lt "$COMP_CWORD" ]]
  do
    local s="${COMP_WORDS[i]}"
    case "$s" in
      -*) ;;
      *)
        cmd="$s"
        break
        ;;
    esac
    (( i++ ))
  done

  if [[ "$i" -eq "$COMP_CWORD" ]]
  then
    local cur="${COMP_WORDS[COMP_CWORD]}"
    COMPREPLY=($(compgen -W "ip wifi stat run stop restart" -- "$cur"))
    return
  fi

  case "$cmd" in
    wifi) _wifi ;;
    *)          ;;
  esac
}


_wifi ()
{
  local i=1 subcommand_index

  while [[ $i -lt $COMP_CWORD ]]; do
    local s="${COMP_WORDS[i]}"
    case "$s" in
    subcommand)
      subcommand_index=$i
      break
      ;;
    esac
    (( i++ ))
  done

  while [[ $subcommand_index -lt $COMP_CWORD ]]; do
    local s="${COMP_WORDS[subcommand_index]}"
    case "$s" in
      connect)
        _wifi_connect
        return
        ;;
      list)
        _wifi_list
        return
        ;;
      disconnect)
        _wifi_disconnect
        return
        ;;
    esac
    (( subcommand_index++ ))
  done

  local cur="${COMP_WORDS[COMP_CWORD]}"
  COMPREPLY=($(compgen -W "list disconnect connect" -- "$cur"))
}

_wifi_connect ()
{
  local cur="${COMP_WORDS[COMP_CWORD]}"
  COMPREPLY=($(compgen -W $(nmcli d wifi | znet_parse_nmcli --list) -- "$cur"))
}

_wifi_list ()
{
  local cur="${COMP_WORDS[COMP_CWORD]}"
  COMPREPLY=()
}

_wifi_disconnect ()
{
  local cur="${COMP_WORDS[COMP_CWORD]}"
  COMPREPLY=()
}

complete -o bashdefault -F _main znet
